<?php

namespace app\admin\controller\dormitory;

use app\admin\model\DormitoryGarden;
use app\admin\model\DormitoryDorm;
use app\common\controller\Backend;
use app\common\model\BehaviorRecord;
use app\common\model\BehaviorRecordDetail;
use EasyWeChat\Foundation\Application;
use think\Db;

class Dorm extends Backend
{
    /**
     * @var \app\admin\model\DormitoryDorm
     */
    protected $model = null;
    protected $searchFields = 'number,name';
    protected $noNeedRight = ['typeList', 'cxSelect', 'floorMaxDorm', 'initBed', 'qrcode', 'dormList', 'floorList', 'qrcodeDetail', 'qrcodeInit', 'buildQrcode'];
    protected $gardenData = [];
    protected $categoryData = [];
    protected $typeData = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('DormitoryDorm');

        $result = collection(DormitoryGarden::all())->toArray();

        foreach ($result as $k => $v) {
            $this->gardenData[$v['number']] = $v['name'];
        }

        $this->categoryData = DormitoryDorm::$categoryList;
        $this->typeData = DormitoryDorm::$typeList;

        //array_pop($this->typeData);

        $this->view->assign('gardenData', $this->gardenData);
        $this->view->assign('categoryData', $this->categoryData);
        $this->view->assign('typeData', $this->typeData);

    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->alias('a')
                ->join('__DORMITORY_GARDEN__ c', 'c.number = a.garden_number', 'left')
                ->join('__DORMITORY_BUILDING__ d', 'd.number = a.building_number and d.garden_number = a.garden_number', 'left')
                ->where($where)
                ->count();

            $list = $this->model
                ->with('creator')
                ->alias('a')
                ->join('__DORMITORY_GARDEN__ c', 'c.number = a.garden_number', 'left')
                ->join('__DORMITORY_BUILDING__ d', 'd.number = a.building_number and d.garden_number = a.garden_number', 'left')
                ->where($where)
                ->field('a.*,c.name as garden_name,d.name as building_name')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            if ($list) {
                //$list = collection($list)->append(['type_text', 'category_text'])->toArray();

                $qrcode = $this->request->request('qrcode', 0);
                $update_data = [];
                foreach ($list as $key => $value) {
                    $list[$key]['type_text'] = isset(DormitoryDorm::$typeList[$value['type']]) ? DormitoryDorm::$typeList[$value['type']] : '';
                    $list[$key]['category_text'] = isset(DormitoryDorm::$categoryList[$value['category']]) ? DormitoryDorm::$categoryList[$value['category']] : '';
                    if (!$value['qrcode']) {
                        $qrcode = DormitoryDorm::generateQrcode($value['id']);
                        $list[$key]['qrcode'] = $qrcode;
                        $update_data[] = [
                            'id' => $value['id'],
                            'qrcode' => $qrcode,
                        ];
                    }
                }

                if ($update_data) {
                    $dorm = new DormitoryDorm;
                    $dorm->saveAll($update_data);
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {

                $params['creator_id'] = $this->auth->id;

                $result = $this->model->validate('DormitoryDorm.add')->save($params);
                if ($result === false) {
                    $this->error($this->model->getError());
                }
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model
            ->alias('a')
            ->join('__DORMITORY_GARDEN__ c', 'c.number = a.garden_number', 'left')
            ->join('__DORMITORY_BUILDING__ d', 'd.number = a.building_number and d.garden_number = a.garden_number', 'left')
            ->where('a.id', $ids)
            ->field('a.*,c.name as garden_name,d.name as building_name')
            ->find();

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {

                $validate = Validate('DormitoryDorm');
                $res = $validate->scene('edit')->check($params);
                if (!$res) {
                    $this->error($validate->getError());
                }

                $params['creator_id'] = $this->auth->id;

                $params['creator_id'] = $this->auth->id;

                // 启动事务
                Db::startTrans();
                try{

                    $row->except(['garden_number', 'building_number', 'number', 'floor'])->save($params);

                    // 提交事务
                    Db::commit();

                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    $this->error($this->model->getError());
                }

                $this->success();
            }
            $this->error();
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 获取寝室类型列表
     */
    public function typeList()
    {
        $typeList = DormitoryDorm::$typeList;

        if ($this->request->get('type', 0))
            array_pop($typeList);

        $data = [];
        foreach ($typeList as $key => $value) {
            $data['searchlist'][] = [
                'id' => $key,
                'name' => $value
            ];
        }

        $this->success('', null, $data);
    }

    /**
     * 联动搜索
     * 根据楼栋号获取寝室列表
     */
    public function cxSelect()
    {
        $garden_number = $this->request->request('garden_number');
        $building_number = $this->request->request('building_number');
        $status = $this->request->request("status", DormitoryDorm::NORMAL);
        $dorm_type = $this->request->request('dorm_type', 0);

        $cond['garden_number'] = $garden_number;
        $cond['building_number'] = $building_number;
        $cond['status'] = $status;
        if ($dorm_type) {
            $cond['type'] = ['in', [$dorm_type, 3]];
            //$cond['type'] = $dorm_type;
        }

        $result = $this->model->where($cond)->select();

        $searchList = [];
        foreach ($result as $key => $value) {
            $searchList[] = ['value' => $value['number'], 'name' => $value['name'], 'id' => $value['id']];
        }

        $this->success('', null, $searchList);
    }

    /**
     * 根据楼栋编号和楼层 获取当前楼层下一个房间号
     */
    public function floorMaxDorm()
    {
        $garden_number = $this->request->request('garden_number');
        $building_number = $this->request->request('building_number');
        $floor = $this->request->request('floor');

        $result = $this->model
            ->where('garden_number', $garden_number)
            ->where('building_number', $building_number)
            ->where('floor', $floor)
            ->field('num,number,name')
            ->order('num', 'desc')
            ->find();

        $data['num'] = '';
        if ($result) {
            $data['num'] = $result->num + 1;
        }

        $this->success('', null, $data);

    }

    public function initBed($ids = '')
    {
        $creator_id = $this->auth->id;

        set_time_limit(0);
        Db::query("call init_dorm_bed($creator_id)");

        $this->success();
    }

    public function qrcode()
    {
        return $this->view->fetch();
    }

    /*public function qrcodeDetail($ids)
    {
        $dorm = $this->model->get($ids);
        if (!$dorm) $this->view->fetch();
        $qrcode = DormitoryDorm::generateQrcode($dorm['id']);
        $dorm->qrcode = $qrcode;
        $dorm->save();

        $this->view->assign("row", $dorm);
        $this->view->fetch();
    }*/

    public function dormList()
    {
        $garden_number = $this->request->request('garden_number');
        $building_number = $this->request->request('building_number');
        $gender = $this->request->request('gender');
        $floor = $this->request->post("floor/a", [], 'strip_tags');
        $status = $this->request->request("status", DormitoryDorm::NORMAL);

        $type = isset(DormitoryDorm::$genderTypeList[$gender]) ? DormitoryDorm::$genderTypeList[$gender] : 0;

        $where['garden_number'] = $garden_number;
        $where['building_number'] = $building_number;
        $where['type'] = $type;
        if ($floor) {
            $where['floor'] = ['in', $floor];
        }

        $data['dorm'] = $this->model
            ->where($where)
            ->where('status', $status)
            ->where('bed_count', 'exp', '> bed_used_count')
            ->field('id,number,name,garden_number,building_number,floor,bed_count,bed_used_count')
            ->select();
        $data['floor'] = [];
        foreach ($data['dorm'] as $key => $value) {
            $data['floor'][$value['floor']] = $value['floor'];
            $data['dorm'][$key]['bed_unused_count'] = $value['bed_count'] - $value['bed_used_count'];
        }
        $data['floor'] = array_values($data['floor']);

        $this->success('', null, $data);
    }

    // 初始化寝室小程序码 每次20个
    public function qrcodeInit()
    {
        set_time_limit(0);
        $dorm_list   = DormitoryDorm::where('qrcode', '')->field('id')->order('id', 'desc')->limit(20)->select();
        $update_data = [];
        foreach ($dorm_list as $key => $value) {
            $qrcode = DormitoryDorm::generateQrcode($value['id']);
            $update_data[] = [
                'id'     => $value['id'],
                'qrcode' => $qrcode,
            ];
        }
        if ($update_data) {
            $dorm = new DormitoryDorm;
            $result = $dorm->isUpdate(true)->saveAll($update_data);

            if ($result) echo 'success';exit;
        }

        echo 'fail';exit;
    }

    public function buildOne()
    {
//        $qrcode = DormitoryDorm::generateQrcode('17600136775', false, true);
//        dd($qrcode);
    }

    public function buildQrcode()
    {
        set_time_limit(0);
        $dorm_list   = DormitoryDorm::alias('dorm')
            ->join('__DORMITORY_GARDEN__ garden', 'garden.number = dorm.garden_number')
            ->join('__DORMITORY_BUILDING__ building', 'building.number = dorm.building_number and building.garden_number = dorm.garden_number')
            ->field('dorm.id,dorm.number,dorm.name,dorm.qrcode,garden.name garden_name,building.name building_name')
            ->order('dorm.id', 'desc')
            ->paginate(500);

        if ($dorm_list) $dorm_list = $dorm_list->toArray();

        $twocode = [];
        foreach ($dorm_list['data'] as $key => $value) {

            if ($value['qrcode']) {
                $qrodeimg = ROOT_PATH . 'public' . $value['qrcode'];
                if (is_file($qrodeimg)) {
                    $qrcode = $value['qrcode'];
                } else {
                    $qrcode = DormitoryDorm::generateQrcode($value['id']);
                    DormitoryDorm::where('id', $value['id'])->update(['qrcode' => $qrcode]);
                }
            } else {
                $qrcode = DormitoryDorm::generateQrcode($value['id']);
                DormitoryDorm::where('id', $value['id'])->update(['qrcode' => $qrcode]);
            }

            $twocode[] = $this->bornshareqrode($qrcode, $value['garden_name'], $value['building_name'], $value['name']);
        }

        echo 11;die;
    }

    //图片处理函数
    function bornshareqrode($qrcode, $garden_name, $building_name, $dorm_name)
    {
        //这是要插入到图片的文字
        $tip1 = "园区：$garden_name";
        $tip2 = "楼栋：$building_name";
        $tip3 = "寝室：$dorm_name";

        $public_path = ROOT_PATH . 'public';
        //这是背景图片的url
        $bannerimg = $public_path . '/uploads/template/sg.jpg';
        //这是需要插入到背景图的图片url
        $qrodeimg = $public_path . $qrcode;;
        if ($bannerimg) {

            //dd($bannerimg);

            //生成中间带logo的二维码
            //这是合成后的图片保存的路径
            $upload_dir = "/uploads/sg-20190919/";
            if (!file_exists($public_path . $upload_dir)) {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($public_path . $upload_dir, 0777,true);
            }
            if (is_file($bannerimg)) {

                //dd($bannerimg);

                //创建画布
                $logo = imagecreatefromstring(file_get_contents($bannerimg));
                $head_img1 = imagecreatefromstring(file_get_contents($qrodeimg));
                //写入文字
                //$black = imagecolorallocate($logo, 66, 108, 119);
                $black = imagecolorallocate($logo, 30,109,182);
                //写的文字用到的字体
                $font = $public_path . '/webfont/simhei.ttf';
                //在图片里插入文字($msg,$black,$grey)
                //imagettftext($logo, 40, 0, 440, 315, $black, $font, $tip1);
                imagettftext($logo, 16, 0, 100, 400, $black, $font, $tip1);
                imagettftext($logo, 16, 0, 100, 430, $black, $font, $tip2);
                imagettftext($logo, 16, 0, 100, 460, $black, $font, $tip3);

                //将$qrodeimg插入到$bannerimg里
                /*$dst_image：新建的图片
                $src_image：需要载入的图片
                $dst_x：设定需要载入的图片在新图中的x坐标
                $dst_y：设定需要载入的图片在新图中的y坐标
                $src_x：设定载入图片要载入的区域x坐标
                $src_y：设定载入图片要载入的区域y坐标
                $dst_w：设定载入的原图的宽度（在此设置缩放）
                $dst_h：设定载入的原图的高度（在此设置缩放）
                $src_w：原图要载入的宽度
                $src_h：原图要载入的高度*/
                //imagecopyresampled($logo, $head_img1, 845, 280, 0, 0, 275, 275, imagesx($head_img1), imagesy($head_img1));
                imagecopyresampled($logo, $head_img1, 0, 0, 0, 0, 354, 354, imagesx($head_img1), imagesy($head_img1));
                //生成图片

                //dd($public_path . $upload_dir . $tip1 . '.png');
                //imagepng($logo, $public_path . $upload_dir . "$garden_name-$building_name-$dorm_name" . '.png');
                //生成图片名字
                //$twocode = $upload_dir . "$garden_name-$building_name-$dorm_name" . '.png'; //如果存在logo就生成带logo的

                imagejpeg($logo, $public_path . $upload_dir . "$garden_name-$building_name-$dorm_name" . '.jpg');
                $twocode = $upload_dir . "$garden_name-$building_name-$dorm_name" . '.jpg'; //如果存在logo就生成带logo的

                // 修改为300分辨率
                $file = $public_path . $upload_dir . "$garden_name-$building_name-$dorm_name" . '.jpg';
                $image = file_get_contents($file);
                $images = substr_replace($image, pack("Cnn", 0x01, 300, 300), 13, 5);
                file_put_contents($file, $images);

                return $twocode;//返回结果图片url
            } else {
                return false;
            }
        } else {
            return false;
        }
    }




    public function ranking()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->alias('a')
                ->join('__DORMITORY_GARDEN__ c', 'c.number = a.garden_number', 'left')
                ->join('__DORMITORY_BUILDING__ d', 'd.number = a.building_number and d.garden_number = a.garden_number', 'left')
                ->where($where)
                ->count();

            $list = $this->model
                ->alias('a')
                ->join('__DORMITORY_GARDEN__ c', 'c.number = a.garden_number', 'left')
                ->join('__DORMITORY_BUILDING__ d', 'd.number = a.building_number and d.garden_number = a.garden_number', 'left')
                ->where($where)
                ->field('a.*,c.name as garden_name,d.name as building_name')
                ->order('a.total_score', 'desc')
                ->limit($offset, $limit)
                ->select();

            if ($list) {
                // 第一个是分数最大的
                $max = current($list);
                // 获取比当前最大分分数高的人数
                $count = DormitoryDorm::where('total_score', '>', $max['total_score'])->count();

                // 当前分数最大的人 的排名
                $sort = 1;
                if ($count) $sort = $count + 1;

                foreach ($list as $key => $value) {
                    $list[$key]['num'] = $offset + $key + 1;

                    //数组中第一个是当前分数最高的 排名为$sort
                    if ($key == 0) {
                        $list[$key]['sort'] = $sort;
                    } else {
                        // 继续循环
                        // 如果当前的分数与上一个的相等 那么就与上一个的排名并列
                        if ($list[$key - 1]['total_score'] == $value['total_score']) {
                            $list[$key]['sort'] = $list[$key - 1]['sort'];
                        } else {
                            $list[$key]['sort'] = $list[$key]['num'];
                        }
                    }

                    $sort++;
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function record()
    {
        $dorm_id = $this->request->request('dorm_id');
        $this->assignconfig("dorm_id", $dorm_id);

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            $dorm = DormitoryDorm::get($dorm_id);

            if (!$dorm) {
                $result = array("total" => 0, "rows" => []);
                return json($result);
            }

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $cond['b.garden_number'] = $dorm['garden_number'];
            $cond['b.building_number'] = $dorm['building_number'];
            $cond['b.dorm_number'] = $dorm['number'];
            $cond['b.student_id'] = 0;
            $total = BehaviorRecordDetail::alias('a')
                ->join('__BEHAVIOR_RECORD__ b', 'b.id = a.record_id', 'left')
                ->where($where)
                ->where($cond)
                ->count();

            $list = BehaviorRecordDetail::alias('a')
                ->join('__BEHAVIOR_RECORD__ b', 'b.id = a.record_id', 'left')
                ->where($where)
                ->where($cond)
                ->field('a.id,b.record_user_group,b.created_at,a.score,a.behavior_name')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function delRecord($ids = "")
    {


//        if ($ids) {
//            $ids = explode(',', $ids);
//            $ids = array_unique($ids);
//
//            $record_detail_list = BehaviorRecordDetail::where('id', 'in', $ids)->select();
//
//            foreach ($record_detail_list as $key => $value) {
//
//                Db::startTrans();
//                try {
//                    $record = BehaviorRecord::where('id', $value['record_id'])->find();
//
//                    if (!$record) continue;
//
//                    $dorm = DormitoryDorm::where('garden_number', $record['garden_number'])
//                        ->where('building_number', $record['building_number'])
//                        ->where('number', $record['dorm_number'])
//                        ->find();
//
//                    if (!$dorm) continue;
//
//                    // 判断删除的事学生分 还是 寝室分
//                    if ($record['student_id']) {
//
//                        $result = model\BehaviorRecord::alias('a')
//                            ->join('__BEHAVIOR_RECORD_DETAIL__ b', 'b.record_id = a.id')
//                            ->where('a.garden_number', $record['garden_number'])
//                            ->where('a.building_number', $record['building_number'])
//                            ->where('a.dorm_number', $record['dorm_number'])
//                            ->where('a.student_id', '>', 0)
//                            ->where('a.id', $record['id'])
//                            ->field('COUNT(DISTINCT(a.student_id)) student_count,SUM(b.score) student_score')
//                            ->find();
//
//                        $student_count = $result['student_count'] ? $result['student_count'] : 0;
//                        $student_score = $result['student_score'] ? $result['student_score'] : 0;
//
//                        $score = 0;
//                        if ($student_count)
//                            $score = (float)number_format(($student_score - $value['score']) / $student_count, 2, '.', '');
//
//                        $dorm->total_score = $dorm['score'] + $score;
//                        $dorm->save();
//
//                        $this->model->where('id', $record['student_id'])->setDec('score', $value['score']);
//
//                    } else {
//
//                        $dorm->setDec('score', $value['score']);
//                        $dorm->setDec('total_score', $value['score']);
//                    }
//
//                    BehaviorRecordDetail::where('id', $value['id'])->delete();
//
//                    // 提交事务
//                    Db::commit();
//
//                } catch (\Exception $e) {
//                    // 回滚事务
//                    Db::rollback();
//
//                    $this->error($e->getMessage() ? $e->getMessage() : '删除失败');
//                }
//            }
//
//            $this->success();
//        }
//
//        $this->error();
    }

}
